package cn.harry.cabinet.api

import android.content.Context
import android.util.Log
import cn.harry.cabinet.api.dto.ExternalApiResponse
import cn.harry.cabinet.api.dto.ItemOperationRecordBody
import cn.harry.cabinet.api.dto.RecognitionRecordBody
import cn.harry.cabinet.api.dto.UserOperationBody
import cn.harry.cabinet.api.enums.ExternalServiceType
import cn.harry.cabinet.model.entity.User
import kotlinx.serialization.InternalSerializationApi
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 外部API服务
 * 提供便捷的API调用方法
 */
class ExternalApiService(context: Context) {
    
    companion object {
        private const val TAG = "ExternalApiService"
        
        @Volatile
        private var instance: ExternalApiService? = null
        
        /**
         * 获取单例实例
         */
        fun getInstance(context: Context): ExternalApiService {
            return instance ?: synchronized(this) {
                instance ?: ExternalApiService(context.applicationContext).also {
                    instance = it
                }
            }
        }
    }
    
    private val apiClient = ExternalApiClient.getInstance(context)
    
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    
    /**
     * 新增用户
     */
    @OptIn(InternalSerializationApi::class)
    suspend fun addUser(user: User): Result<ExternalApiResponse<String>> {
        val body = UserOperationBody(
            id = user.id,
            employeeId = user.employeeId,
            name = user.name,
            phoneNumber = user.phoneNumber,
            position = user.position,
            gender = user.gender.name,
            status = user.status.name,
            featureCode = user.featureCode,
            password = user.password
        )
        
        return apiClient.sendRequest(
            ExternalServiceType.ADD_USER,
            body
        )
    }
    
    /**
     * 修改用户
     */
    @OptIn(InternalSerializationApi::class)
    suspend fun updateUser(user: User): Result<ExternalApiResponse<String>> {
        val body = UserOperationBody(
            id = user.id,
            employeeId = user.employeeId,
            name = user.name,
            phoneNumber = user.phoneNumber,
            position = user.position,
            gender = user.gender.name,
            status = user.status.name,
            featureCode = user.featureCode,
            password = user.password
        )
        
        return apiClient.sendRequest(
            ExternalServiceType.UPDATE_USER,
            body
        )
    }
    
    /**
     * 删除用户
     */
    @OptIn(InternalSerializationApi::class)
    suspend fun deleteUser(userId: Long, employeeId: String): Result<ExternalApiResponse<String>> {
        val body = UserOperationBody(
            id = userId,
            employeeId = employeeId,
        )
        
        return apiClient.sendRequest(
            ExternalServiceType.DELETE_USER,
            body
        )
    }
    
    /**
     * 上报人脸识别记录
     */
    @OptIn(InternalSerializationApi::class)
    suspend fun reportFaceRecognition(
        userId: Long,
        userName: String,
        result: String,
        confidence: Float
    ): Result<ExternalApiResponse<String>> {
        val body = RecognitionRecordBody(
            userId = userId,
            userName = userName,
            recognitionType = "face",
            recognitionTime = dateFormat.format(Date()),
            result = result,
            confidence = confidence
        )
        
        return apiClient.sendRequest(
            ExternalServiceType.FACE_RECOGNITION_RECORD,
            body
        )
    }
    
    /**
     * 上报刷卡记录
     */
    @OptIn(InternalSerializationApi::class)
    suspend fun reportCardSwipe(
        userId: Long,
        userName: String,
        cardNumber: String,
        result: String
    ): Result<ExternalApiResponse<String>> {
        val body = RecognitionRecordBody(
            userId = userId,
            userName = userName,
            recognitionType = "card",
            recognitionTime = dateFormat.format(Date()),
            result = result,
            cardNumber = cardNumber
        )
        
        return apiClient.sendRequest(
            ExternalServiceType.CARD_SWIPE_RECORD,
            body
        )
    }
    
    /**
     * 上报取物记录
     */
    @OptIn(InternalSerializationApi::class)
    suspend fun reportTakeItem(
        userId: Long,
        userName: String,
        itemInfo: String? = null,
        remark: String? = null
    ): Result<ExternalApiResponse<String>> {
        val body = ItemOperationRecordBody(
            userId = userId,
            userName = userName,
            operationType = "take",
            operationTime = dateFormat.format(Date()),
            itemInfo = itemInfo,
            remark = remark
        )
        
        return apiClient.sendRequest(
            ExternalServiceType.TAKE_ITEM_RECORD,
            body
        )
    }
    
    /**
     * 上报还物记录
     */
    @OptIn(InternalSerializationApi::class)
    suspend fun reportReturnItem(
        userId: Long,
        userName: String,
        itemInfo: String? = null,
        remark: String? = null
    ): Result<ExternalApiResponse<String>> {
        val body = ItemOperationRecordBody(
            userId = userId,
            userName = userName,
            operationType = "return",
            operationTime = dateFormat.format(Date()),
            itemInfo = itemInfo,
            remark = remark
        )
        
        return apiClient.sendRequest(
            ExternalServiceType.RETURN_ITEM_RECORD,
            body
        )
    }
    

    // ==================== 统一通知方法 ====================
    
    /**
     * 通知外部接口用户操作
     * @param user 用户对象
     * @param operationType 操作类型
     */
    @OptIn(InternalSerializationApi::class)
    suspend fun notifyUserOperation(user: User, operationType: ExternalServiceType) {
        try {
            val result = when (operationType) {
                ExternalServiceType.ADD_USER -> addUser(user)
                ExternalServiceType.UPDATE_USER -> updateUser(user)
                ExternalServiceType.DELETE_USER -> deleteUser(user.id, user.employeeId)
                ExternalServiceType.FACE_RECOGNITION_RECORD -> TODO()
                ExternalServiceType.CARD_SWIPE_RECORD -> TODO()
                ExternalServiceType.TAKE_ITEM_RECORD -> TODO()
                ExternalServiceType.RETURN_ITEM_RECORD -> TODO()
            }
            
            result.onSuccess { response ->
                if (response.success) {
                    Log.d(TAG, "外部接口通知成功：${operationType.description} ${user.name}")
                } else {
                    Log.w(TAG, "外部接口通知失败：${response.message}")
                }
            }.onFailure { error ->
                Log.e(TAG, "外部接口通知异常：${error.message}")
            }
        } catch (e: Exception) {
            Log.e(TAG, "通知外部接口失败：${e.message}", e)
        }
    }
}
